<?php
/**
 * Authentication plugin
 *
 * @author Lukas Normantas
 */
class Areal_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        $auth = Zend_Auth::getInstance();
        $view = Zend_Layout::getMvcInstance()->getView();

        // if login form posted then try to authenticate
        $loginForm = new Default_LoginForm();
        if ( $this->getRequest()->isPost() ) {
            if ($loginForm->isValid( $this->getRequest()->getPost() )) {
                $identity = new Areal_Auth_Identity();
                $identity->setEmail($loginForm->getValue('login_email'));
                $identity->setPassword($loginForm->getValue('login_password'));
                $result = $auth->authenticate($identity);
                if ( $result->getCode() !== Zend_Auth_Result::SUCCESS ) {
                    $view->flashMessenger()->addMessage('ne-pasijunge');
                } else {
                    $view->flashMessenger()->addMessage('pasijunge');
                    //return $this->_helper->redirector('index','index','default');
                }
            }
        }

        // make login form accessible in views
        $view->loginForm = $loginForm;

        // If no user loged in creates a new user with guest role
        if ( ! $auth->hasIdentity()){
            $auth->authenticate( new Areal_Auth_Identity_Guest() );
        }

        // make identity accessible in views
        $view->identity = $auth->getIdentity();
    }
}